//
//  WYComposeTextView.swift
//  WYWeibo
//
//  Created by wangyi on 16/7/22.
//  Copyright © 2016年 wangyi. All rights reserved.
//

import UIKit

class WYComposeTextView: UITextView {
    
    //MARK: -- 懒加载
    private lazy var placeHoldLabel: UILabel = {
    
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(12)
        label.text = "人会傻的......"
        //多行显示
        label.numberOfLines = 0
        label.textColor = UIColor.lightGrayColor()
        return label
    }()
    //占位文字  给 xib 添加在设置属性
    @IBInspectable var placeHolder: String? {
    
        didSet {
            
            placeHoldLabel.text = placeHolder
        }
    }
    
    //重写 font 
    override var font: UIFont? {
    
        didSet{
        
            //如果外界传入nil 直接返回
            if font == nil {
            
                return
            }
            placeHoldLabel.font = font
        }
        
    }
    //重写 text 
    override var text: String? {
    
        didSet{
            placeHoldLabel.hidden = hasText()
        }
    }
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setUPUI()
    }
    //加载 XIB
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        setUPUI()
//        fatalError("init(coder:) has not been implemented")
    }
    //添加控件约束
    private func setUPUI() {
     
        //监听 UItextView文字改变的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textChange", name: UITextViewTextDidChangeNotification, object: nil)
        //添加控件
        addSubview(placeHoldLabel)
        
        //自动布局 关闭
        placeHoldLabel.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: placeHoldLabel, attribute: .Leading, relatedBy: .Equal, toItem: self, attribute: .Leading, multiplier: 1, constant: 5))
        addConstraint(NSLayoutConstraint(item: placeHoldLabel, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 8))
        addConstraint(NSLayoutConstraint(item: placeHoldLabel, attribute: .Width, relatedBy: .Equal, toItem: self, attribute: .Width, multiplier: 1, constant: -10))
    }
    
    //MARK: -- 监听文字改变的方法
    @objc private func textChange() {
    
        //判断有内容的话就隐藏站位 label
        placeHoldLabel.hidden = self.hasText()
    }
    
    deinit {
    
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}
